package com.sjb.stock.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @FileName RedisCacheConfig
 * @Description  定义redisTemplate的配置
 * @Author chm
 * @date 2025/7/5
 **/
@Configuration
public class RedisCacheConfig {

    /**
     * @description: 当yml中配置了reids数据源的基本信息，底层会自动构建好RedisConnectionFactory连接工厂
     * @param connectionFactory redis的连接工厂 通过方法入参形式，将容器中的RedisConnectionFactory注入到方法下
     * @return org.springframework.data.redis.core.RedisTemplate
     * @author chm
     * @date 2025/7/5
     **/
    @Bean
    public RedisTemplate redisTemplate(@Autowired RedisConnectionFactory connectionFactory){
        // 定义模板对象
        RedisTemplate<String,Object> redisTemplate=new RedisTemplate<>();
        // 设置序列化方式
        StringRedisSerializer keySerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer<Object> jsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        // 替换原有的jdk序列化方式
        redisTemplate.setKeySerializer(keySerializer);
        redisTemplate.setHashKeySerializer(keySerializer);
        redisTemplate.setValueSerializer(jsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jsonRedisSerializer);
        // 设置工厂
        redisTemplate.setConnectionFactory(connectionFactory);
        // 初始化设置
        redisTemplate.afterPropertiesSet();
        return  redisTemplate;
    }
}
